package com.yingsheng.bi.hks.template.processor;

import com.yingsheng.bi.hks.template.events.AdviceEvent;
import com.yingsheng.bi.hks.template.events.Event;

public class IfElseProcessor implements Processor {

    private int order;

    private Processor condition;

    private Processor ifThen;

    private Processor elseThen;

    @Override
    public void exec(Event event) {
        if (event instanceof AdviceEvent) {
            AdviceEvent adviceEvent = (AdviceEvent) event;
            if (condition(adviceEvent)) {
                ifThen.exec(event);
            } else {
                elseThen.exec(event);
            }
        }
    }

    private boolean condition(AdviceEvent event) {
        Object output = event.getOutput();
        try {
            event.setOutput(null);
            condition.exec(event);
            Object conditionOutput = event.getOutput();
            if (conditionOutput != null && conditionOutput instanceof Boolean) {
                return (Boolean) conditionOutput;
            }
        } finally {
            event.setOutput(output);
        }
        return false;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public Processor getCondition() {
        return condition;
    }

    public void setCondition(Processor condition) {
        this.condition = condition;
    }

    public Processor getIfThen() {
        return ifThen;
    }

    public void setIfThen(Processor ifThen) {
        this.ifThen = ifThen;
    }

    public Processor getElseThen() {
        return elseThen;
    }

    public void setElseThen(Processor elseThen) {
        this.elseThen = elseThen;
    }
}
